<?php
class mdl_member_vote extends ujn_model {
	const MEM_DAY_VOTE_NUM_KEY = 'day_vote_num';
	
	const max_vote_num = 100;
	
	public function getSurplus($mid) {
		return mdl_member_limit::getInstance()->getSurplus($mid, mdl_member_vote::MEM_DAY_VOTE_NUM_KEY, mdl_member_vote::max_vote_num);
	}
	
	public function check($mid) {
		return mdl_member_limit::getInstance()->check($mid, mdl_member_vote::MEM_DAY_VOTE_NUM_KEY, mdl_member_vote::max_vote_num);
	}
	
	public function increment($mid) {
		if( !$mid = tls_func::uint($mid) ) {
			return false;
		}
		
		return mdl_member_limit::getInstance()->increment($mid, mdl_member_vote::MEM_DAY_VOTE_NUM_KEY, mktime(7,0,0,date('m'),date('d')+1) - NOW);
	}
	public function vote($mid, $l_sitemid, $r_sitemid, $w) {	
		if( !$mid = tls_func::uint($mid) ) {
			return false;
		}
		$w = tls_func::uint($w);
		$l_sitemid = tls_func::escape($l_sitemid);
		$r_sitemid = tls_func::escape($r_sitemid);
		
		$l_sitemid_win = 0;
		$l_sitemid_loss = 0;
		$r_sitemid_win = 0;
		$r_sitemid_loss = 0;		
		if($w == 0) {
			$l_sitemid_win = 1;
			$r_sitemid_loss = 1;
		}else {
			$r_sitemid_win = 1;
			$l_sitemid_loss = 1;
		}
		$_sql_l = "UPDATE {$this->tbl_name} SET `wins` = `wins` + $l_sitemid_win, `losses` = `losses` + $l_sitemid_loss WHERE sitemid = '{$l_sitemid}'";
		$_sql_r = "UPDATE {$this->tbl_name} SET `wins` = `wins` + $r_sitemid_win, `losses` = `losses` + $r_sitemid_loss WHERE sitemid = '{$r_sitemid}'";
		$this->_db->query($_sql_l);
		$this->_db->query($_sql_r);
		
		$this->increment($mid);

		return mdl_member_history::getInstance()->log($mid, $l_sitemid, $r_sitemid, $w);
	}
	
	public function rand($sex, $limit = 2) {
		$sex = $this->getIsomerism($sex);
		$_sql = "SELECT * FROM {$this->tbl_name} WHERE sex = '{$sex}' ORDER BY RAND() LIMIT {$limit}";
		return $this->_db->getAll($_sql);
	}
	
	public function search($sitemids = array()) {
		if(count($sitemids) <= 0) return array();
		
		$_sql = "SELECT * FROM {$this->tbl_name} WHERE sitemid in (" . implode(',', $sitemids) . ")";
		return $this->_db->getAll($_sql);
	}
	
	public function saveUser($users) {
		if(count($users) <= 0) return false;
		
		$_sql = "INSERT INTO {$this->tbl_name} (sitemid, sex) VALUES ";
		foreach($users as $sitemid => $sex) {
			$_sql .= "('{$sitemid}', '{$sex}'), ";
		}
		$_sql = substr($_sql, 0, -2);
		
		$this->_db->query($_sql);
		
		return true;
	}
	
	public function getIsomerism($sex) {
		$sex = ($sex + 1) % 2;
		return $sex;
	}
	
	protected function __construct() {
		parent::__construct();
		$this->db_name		= 'love_a_love';
		$this->tbl_name		= "`{$this->db_name}`.`love_vote`";
		$this->_db			= $this->mysql();
	}


    /**
     * 单例模型
     * @return mdl_member_vote
     */
	static function getInstance() {
        return parent::getInstance(__CLASS__);
	}	
}
